package com.study.manage.mvc.org.authentication;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import com.study.manage.dal.NotificationRepository;
import com.study.manage.dal.SmsBatchRepository;
import com.study.manage.dal.UserDetailRepository;
import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.Notification;
import com.study.manage.domain.SmsBatch;
import com.study.manage.domain.User;
import com.study.manage.domain.UserDetail;
import com.study.manage.domain.UserOrganiza;
import com.study.manage.domain.enumm.NotificationShowType;
import com.study.manage.domain.enumm.NotificationState;
import com.study.manage.domain.enumm.NotificationType;
import com.study.manage.domain.enumm.UserSmsState;
import com.study.manage.domain.enumm.UserType;
import com.study.manage.dto.BaseProperties;
import com.study.manage.utils.JsonMapper;
import com.study.manage.utils.ManageUtils;

@Service
public class RZService extends BaseProperties {

    @Value("${study.qiniu.ak}")
    protected String ak;

    @Value("${study.qiniu.sk}")
    protected String sk;

    @Value("${study.qiniu.zone}")
    protected String zone;

    @Value("${study.qiniu.url}")
    protected String qiniuUrl;

    @Autowired
    private UserOrganizaRepository userOrganizaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserDetailRepository userDetailRepository;
    @Autowired
    private NotificationRepository notificationRepository;
    @Autowired
    private SmsBatchRepository smsBatchRepository;

    private JsonMapper jsonMapper = new JsonMapper();

    @Transactional
    public void rz(Long userId, UserOrganiza userOrganiza) {
        UserOrganiza uo = userOrganizaRepository.findByRegUserId(userId);
        if (uo != null) {
            userOrganiza.id = uo.id;
            userOrganiza.userId = uo.userId;
        }
        userOrganiza.regUserId = userId;
        userOrganizaRepository.save(userOrganiza);
        User regUser = userRepository.findOne(userId);
        // 还未认证成机构
        if (userOrganiza.userId == null) {
            long number = 0;
            User u = null;
            do {
                number = ManageUtils.getNumber(5);
                u = userRepository.findByNumber(number);
            } while (u != null);
            u = new User();
            u.type = UserType.ORG;
            u.salt = userOrganiza.salt;
            u.hashPassword = userOrganiza.hashPassword;
            u.number = number;
            u.name = userOrganiza.name;
            u.inviteCode = ManageUtils.randomLetterStr(6);
            u.email = userOrganiza.email;
            userRepository.save(u);

            UserDetail ud = userDetailRepository.findByUserId(userId);
            UserDetail newUd = new UserDetail();
            newUd.realName = userOrganiza.name;
            newUd.addressDetail = userOrganiza.mailAddress;
            newUd.nickName = userOrganiza.name;
            if (!StringUtils.isEmpty(userOrganiza.tags)) {
                String[] uos = userOrganiza.tags.split(",");
                List<Long> tagIds = new ArrayList<>();
                newUd.teachingsText = "";
                for (String uot : uos) {
                    tagIds.add(Long.valueOf(uot));
                    newUd.teachingsText += "-" + uot + "-";
                }
                newUd.teachings = jsonMapper.toJson(tagIds);
            }
            newUd.userId = u.id;
            newUd.qudao = ud.qudao;
            userDetailRepository.save(newUd);

            userOrganiza.userId = u.id;
            userOrganizaRepository.save(userOrganiza);
            if (!StringUtils.isEmpty(userOrganiza.idImg4)) {
                try {
                    BucketManager bucketManager = new BucketManager(Auth.create(ak, sk));
                    bucketManager.fetch(userOrganiza.idImg4, zone, "pic_avatar_" + number + ".jpg");
                } catch (Exception e) {
                    // LOGGER.error("upload image error", e);
                }
            } else {
                u = userRepository.findOne(userOrganiza.userId);
            }

            Notification notification = new Notification();
            notification.type = NotificationType.SYS;
            notification.state = NotificationState.UNREAD;
            notification.name = "我要学";
            notification.avatar = "001";
            notification.msg = "审核通知：您的“机构”用户已注册成功，欢迎入驻我要学！请及时补充资料认证，成为“认证机构”后您将拥有完整版的机构功能及平台展示。";
            notification.userId = u.id;
            notification.showType = NotificationShowType.TEXT;
            notificationRepository.save(notification);
            sendSms(regUser.phone, notification.msg, null);
        }
    }


    public void sendSms(String phone, String msg, String ip) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            SmsBatch smsBatch = new SmsBatch();
            smsBatch.count = 1;
            smsBatch.phone = phone;
            smsBatch.msg = msg;
            smsBatch.state = UserSmsState.SUCCESS;
            smsBatch.response = UserSmsState.SUCCESS.desc;
            HttpPost httpPost = new HttpPost(smsSendUrl);
            List<NameValuePair> nvps = Lists.newArrayList();
            nvps.add(new BasicNameValuePair("apikey", smsApiKey));
            nvps.add(new BasicNameValuePair("mobile", phone));
            nvps.add(new BasicNameValuePair("text", msg));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                String json = EntityUtils.toString(response.getEntity());
                smsBatch.response = json;
                if (json.startsWith("{\"code\":0")) {
                    smsBatch.state = UserSmsState.SUCCESS;
                } else {
                    smsBatch.state = UserSmsState.FAILURE;
                }
            } finally {
                httpclient.close();
            }
            smsBatchRepository.save(smsBatch);
        } catch (Exception e) {
        }
    }

}
